﻿@page "/Courses/CoursePage/ChapterPage"
@layout ChapterLayout
@inject CourseService CourseService
@inject NavigationManager Navigation
@inject AuthenticationStateProvider AuthStateProvider
@inject CourseService CourseService
@inject CourseStateService NavState
@inject Blazored.LocalStorage.ILocalStorageService localStorage
@attribute [Authorize]
@using Microsoft.AspNetCore.Authorization
@using AntDesign
@using lcwb.Shared.Service
@using lcwb.Shared.Model

<h2>@Chapter?.Title</h2>
<div>Chapter Resource</div>
<Paragraph>
    @((MarkupString)MarkdownHtml)
</Paragraph>
<lcwb.Pages.Course.Components.VideoCell></lcwb.Pages.Course.Components.VideoCell>

@code {
    private Chapter Chapter { get; set; }
    // If have multiple, List<Resource>
    // Resource is markdown -> RenderFrame -> <div> or Video
    // Markdown -> ImageURL
    private string MarkdownHtml = "";

    protected override async Task OnInitializedAsync()
    {
        NavState.OnStateChange += StateChanged;
        await LoadChapterData();
    }

    private async Task LoadChapterData()
    {

        if (NavState.CurrentChapterId.HasValue && NavState.CurrentCourseId.HasValue)
        {
            Chapter = await CourseService.GetChapterById(NavState.CurrentChapterId.Value);
            // ChapterResourceService
            var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
            // mock data
            string markdown = "## 变量\n\n### 1. 变量的定义\n- 在C语言中，变量是用于存储数据的命名存储位置。\n- 定义变量时需要指定其数据类型，例如：`int`、`float`、`char`。\n\n### 2. 变量的初始化\n- 变量可以在定义时初始化，例如：\n  - `int age = 25;`\n  - `float height = 175.5;`\n  - `char grade = 'A';`\n\n### 3. 数据类型\n- **整型（int）**：用于存储整数，例如年龄。\n- **浮点型（float/double）**：用于存储带小数点的数字，例如身高。\n- **字符型（char）**：用于存储单个字符，例如成绩等级。\n\n### 4. 变量的作用域\n- **局部变量**：在函数或代码块内定义，只能在该范围内使用。\n- **全局变量**：在函数外部定义，可以在整个程序中使用。\n\n### 5. 常量\n- 使用`const`关键字定义常量，其值在程序运行期间不可更改。例如：\n  - `const float PI = 3.14159;`\n\n### 示例代码\n```c\n#include <stdio.h>\n\nint main() {\n    int age = 25;\n    float height = 175.5;\n    char grade = 'A';\n\n    printf(\"Age: %d\\n\", age);\n    printf(\"Height: %.2f\\n\", height);\n    printf(\"Grade: %c\\n\", grade);\n\n    return 0;\n}\n```\n\n### 注意事项\n- 变量名只能包含字母、数字和下划线，且不能以数字开头。\n- 变量名区分大小写，例如`age`和`Age`是两个不同的变量。\n- 建议使用有意义的变量名以提高代码可读性。";
            MarkdownHtml = Markdig.Markdown.ToHtml(markdown, pipeline);
        }
        else if (NavState.CurrentChapterId.HasValue && !NavState.CurrentCourseId.HasValue)
        {
            string URL = $"/Courses/CoursePage";
            Navigation.NavigateTo(URL);
        }
        else
        {
            string URL = $"/Courses";
            Navigation.NavigateTo(URL);
        }
    }

    private void StateChanged()
    {
        StateHasChanged();
        _ = LoadChapterData();
    }

    public void Dispose()
    {
        NavState.OnStateChange -= StateChanged;
    }
}